<template>
  <div>
    <div v-if="!disabled" class="upload-tip">{{ '支持上传' + accept }}，最多可上传{{ limit }}个</div>
    <div class="upload-img_list">
      <div v-for="(item, index) in fileDataModel" :key="index + 'img'">
        <div class="upload-img_box" @click="handleShowFile(item.filePath)">
          <img v-if="fileWord.includes(item.type)" class="upload-img" src="@/assets/imgs/doc.png" alt="">
          <img v-if="filePdf.includes(item.type)" class="upload-img" src="@/assets/imgs/pdf.png" alt="">
          <img v-if="fileXlsx.includes(item.type)" class="upload-img" src="@/assets/imgs/excl.png" alt="">
          <img v-if="fileZip.includes(item.type)" class="upload-img" src="@/assets/imgs/rar.png" alt="">
          <img v-if="fileImg.includes(item.type)" class="upload-img" :src="origin + item.filePath" alt="">
          <img v-if="$route.query.type !== 'VIEW'&&!disabled" class="upload-close" src="@/assets/imgs/close.png" alt="" @click.stop="handleDeleteFile(index)">
        </div>
        <el-popover placement="top-start" width="200" trigger="hover" :content="item.fileName">
          <div slot="reference" class="file-name overHidden">{{ item.fileName }}</div>
        </el-popover>
      </div>
      <el-upload
        v-if="fileDataModel.length < limit && !disabled"
        ref="uploadComponent"
        action="/jkb-jkcz/api/oss/uploadFileNew"
        :limit="limit"
        :show-file-list="false"
        :on-progress="handleOnProcess"
        :before-upload="beforeUpload"
        :file-list="fileList"
        :accept="accept"
        :multiple="multiple"
        :headers="headers"
        :data="{ module }"
        :on-success="onSuccess"
        :on-error="onError"
      >
        <div class="upload-img_box upload-box">
          <span class="up-txt">上传文件</span>
          <span class="add-icon el-icon-plus" />
        </div>
      </el-upload>
    </div>
    <div v-if="!disabled" style="height: 6px">
      <el-progress v-show="progressFlag" :percentage="loadProgress" />
    </div>
  </div>
</template>

<script>
// import { uploadFileNew } from '@/api/common';
import { getFileNameAndSuffix } from '@/utils';
import { getToken } from '@/utils/cache';

export default {
  props: {
    disabled: {
      type: Boolean,
      default: false
    },
    multiple: {
      type: Boolean,
      default: false
    },
    accept: {
      type: String,
      default: 'image/*,.pdf,.PDF'
    },
    module: {
      type: String,
      default: ''
    },
    limit: {
      type: Number,
      default: 1
    },
    maxSize: {
      type: Number,
      default: 30
    },
    fileData: {
      type: Array,
      default: () => []
    }
  },
  data() {
    return {
      fileList: [],
      loadProgress: 0,
      progressFlag: false,
      fileWord: ['.doc', '.docx'],
      filePdf: ['.pdf'],
      fileXlsx: ['.xls', '.xlsx'],
      fileZip: ['.rar', '.zip'],
      fileImg: ['.png', '.jpg', '.jpeg'],
      origin: window.location.origin,
      headers: {
        access_token: getToken()
      }
    };
  },
  computed: {
    fileDataModel: {
      get() {
        return this.fileData;
      },
      set(v) {
        this.$emit('update:fileData', v);
      }
    }
  },
  methods: {
    handleShowFile(url) {
      window.open(this.origin + url, '_blank');
    },
    handleDeleteFile(index) {
      this.fileDataModel.splice(index, 1);
      this.deleteUploadFile();
    },
    onSuccess({ success, value, exceptionContent }) {
      if (success && value) {
        value.type = getFileNameAndSuffix(value.filePath, 1);
        this.fileDataModel.push(value);
      } else {
        this.$message({
          message: exceptionContent || '上传失败',
          type: 'error'
        });
        this.deleteUploadFile();
      }
    },
    onError(err) {
      this.deleteUploadFile();
      this.$message({
        message: err || '上传失败',
        type: 'error'
      });
    },
    handleOnProcess(event, file, fileList) {
      this.progressFlag = true; // 显示进度条
      this.loadProgress = parseInt(event.percent); // 动态获取文件上传进度
      if (this.loadProgress >= 100) {
        this.loadProgress = 100;
        setTimeout(() => {
          this.progressFlag = false;
          this.loadProgress = 0;
        }, 500);
      }
    },
    beforeUpload(file) {
      if (file.size > this.maxSize * 1000000) {
        this.$message({
          message: `文件过大，请上传${this.maxSize}m以内大小的文件！`,
          type: 'error'
        });
        return false;
      }
      const fileType = getFileNameAndSuffix(file.name, 1);
      if (this.accept == 'image/*,.pdf,.PDF') {
        if (![...this.filePdf, ...this.fileImg].includes(fileType)) {
          this.$message({
            message: `仅支持上传照片、PDF格式的文件！`,
            type: 'error'
          });
          return false;
        }
      } else {
        const fileType = getFileNameAndSuffix(file.name, 1);
        if (!this.accept.includes(fileType)) {
          this.$message({
            message: `不支持上传${fileType}格式的文件！`,
            type: 'success'
          });
          return false;
        }
      }
      return true;
    },
    deleteUploadFile() {
      const files = this.$refs.uploadComponent.uploadFiles;
      files.splice(files.length - 1, 1);
    }
  }
};
</script>

<style scoped lang="scss">
.upload-tip {
  color: rgba(31, 32, 34, 0.5);
  font-size: 14px;
  margin-bottom: 8px;
}
.upload-img_list {
  display: flex;
  .upload-img_box {
    position: relative;
    border: 1px dashed #e1e5eb;
    width: 103px;
    height: 103px;
    cursor: pointer;
    margin-right: 20px;
    .upload-img {
      width: 100%;
      height: 100%;
    }
    .upload-close {
      position: absolute;
      right: 0;
      top: 0;
      width: 20px;
      height: 20px;
    }
  }
  .file-name {
    width: 104px;
    color: rgba(31, 32, 34, 0.5);
    font-size: 14px;
    text-align: center;
  }
  .upload-box {
    text-align: center;
    border: 1px solid #e1e5eb;
    font-size: 14px;
    color: rgba(31, 32, 34, 0.5);
    position: relative;
    .up-txt {
      position: absolute;
      bottom: 25px;
      left: 24px;
    }
    .add-icon {
      font-size: 24px;
      position: absolute;
      left: 40px;
      top: 28px;
    }
  }
}
</style>
